package day14.homework01.test06;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * @author Xiao
 * @date 2021/8/7
 */
public class Bonus2 implements Runnable{
    private Integer[] arr = {85, 100, 60, 10, 50, 20, 22,8};
    private ArrayList<Integer> box = new ArrayList<>();

    //构造代码块：构造方法执行之前会执行一次
    //初始化box
    {
        Collections.addAll(box, arr);
    }

    @Override
    public void run() {
        Random r = new Random();
        int sum = 0;
        while (true) {
            synchronized (this) {
                if (box.size() <= 0) {
                    System.out.println(Thread.currentThread().getName() + "总共抽中了" + sum + "元奖金");
                    break;
                }
                int index = r.nextInt(box.size());
                Integer bonus = box.get(index);
                System.out.println(Thread.currentThread().getName() + "抽中了" + bonus + "元奖金。。。");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum += bonus;
                box.remove(index);
            }
        }
    }
}
class Test {
    public static void main(String[] args) {
        Bonus2 b = new Bonus2();
        Thread t1 = new Thread(b);
        Thread t2 = new Thread(b);
        t1.setName("抽奖箱1");
        t2.setName("抽奖箱2");
        t1.start();
        t2.start();
    }
}
